﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Comm.Utils;
using SYSoft.Model;
using SYSoft.Model.ViewModels.DeviceData;
using SYSoft.Model.ViewModels.DeviceManage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace SYSoft.Controllers.DeviceManage
{
    public class PU3000Controller : BaseController
    {
        /// <summary>
        /// PU3000实时数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel GetRealData()
        {
           var  res = NetFactory.redisPool.ReadHashKey("MTCD:ConstGateWay", DeviceID.PU3000.ToString());
            var res1 = NetFactory.redisPool.ReadKey("MTCD:PU3000Config");
            if (res.IsSuccess)
            {
                PU3000VM pU3000 = new PU3000VM();
                JObject obj = JObject.Parse(res.Content);
                if(obj.Value<bool>("IsActive"))
                {
                    pU3000.Youqi_jiaoban = Convert.ToSingle(obj["Youqi_jiaoban"].ToString());
                    pU3000.Youqi_yuanliao = Convert.ToSingle(obj["Youqi_yuanliao"].ToString());
                    pU3000.Youqi_press = Convert.ToSingle(obj["Youqi_press"].ToString());
                    pU3000.Guhua_jiaoban = Convert.ToSingle(obj["Guhua_jiaoban"].ToString());
                    pU3000.Guhua_press = Convert.ToSingle(obj["Guhua_press"].ToString());
                    pU3000.Guhua_yuanliao = Convert.ToSingle(obj["Guhua_yuanliao"].ToString());

                    pU3000.Youqi_open1 = Convert.ToBoolean(obj["Youqi_open1"].ToString());
                    pU3000.Youqi_switch1 = Convert.ToBoolean(obj["Youqi_switch1"].ToString());
                    pU3000.Guhua_open2 = Convert.ToBoolean(obj["Guhua_open2"].ToString());
                    pU3000.Guhua_switch2 = Convert.ToBoolean(obj["Guhua_switch2"].ToString());

                    pU3000.Youqi_change1 = Convert.ToBoolean(obj["Youqi_change1"].ToString());
                    pU3000.Guhua_change2 = Convert.ToBoolean(obj["Guhua_change2"].ToString());


                    pU3000.Youqi_alarm1 = Convert.ToBoolean(obj["Youqi_alarm1"].ToString());
                    pU3000.Youqi_alarm2 = Convert.ToBoolean(obj["Youqi_alarm2"].ToString());
                    pU3000.Guhua_alarm1 = Convert.ToBoolean(obj["Guhua_alarm1"].ToString());
                    pU3000.Guhua_alarm2 = Convert.ToBoolean(obj["Guhua_alarm2"].ToString());
                    if (res1.IsSuccess)
                    {
                        JObject obj1 = JObject.Parse(res1.Content);

                        pU3000.Chanlaing = Convert.ToInt32(obj1["ChanLiang"].ToString());
                    }
                    return MessageModel.CreateSuccessResult(pU3000);
                }
                else
                {
                    return new MessageModel("设备不在线");
                }                                          
            }
            else
            {
                return new MessageModel(res.Message);
            }
          
        }


        /// <summary>
        /// 获取当日使用量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel TotalDayUsed()
        {
            var res = NetFactory.redisPool.ReadKey("MTCD:STAT:PU3000");
            if (res.IsSuccess)
            {
                PU3000VM_Day pU3000 = new PU3000VM_Day();
                JObject obj = JObject.Parse(res.Content);
                pU3000.TotalGuhuaConsume = Convert.ToSingle(obj["Guhuajiactrueliy"].ToString());
                pU3000.TotalYouqiConsume = Convert.ToSingle(obj["Youqiactrueliy"].ToString());
                pU3000.Peibi = Convert.ToSingle(obj["Peibi"].ToString());
                return MessageModel.CreateSuccessResult(pU3000);
            }
            else
            {
                return new MessageModel(res.Message);
            }
        }


        [HttpGet]
        public MessageModel GetPU3000ConfigData()
        {
            var res = NetFactory.redisPool.ReadKey("MTCD:PU3000Config");
            if (res.IsSuccess)
            {
                PU3000ConfigVM pU3000 = new PU3000ConfigVM();
                JObject obj = JObject.Parse(res.Content);
                pU3000.PeopleName = obj["PeopleName"].ToString();
                pU3000.Spece = obj["Spece"].ToString();
                pU3000.Bom = obj["Bom"].ToString();
                pU3000.Peibi = obj["Peibi"].ToString();
                pU3000.SerialNo = obj["SerialNo"].ToString();
                pU3000.RealBom =Convert.ToSingle( obj["RealBom"]);
                pU3000.RealPeibi = Convert.ToSingle(obj["RealPeibi"]);
                pU3000.RealUsingAlarm = Convert.ToBoolean(obj["RealUsingAlarm"]);
                pU3000.RealPeibiAlarm = Convert.ToBoolean(obj["RealPeibiAlarm"]);
                return MessageModel.CreateSuccessResult(pU3000);
            }
            else
            {
                return new MessageModel(res.Message);
            }
        }

        /// <summary>
        /// 获取当月使用量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel TotalMonthUsed()
        {
            MysqlHelper mysql = new MysqlHelper();
            DateTime dt = Convert.ToDateTime(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString()+"-"+"1"+ " 00:00:00");
            string sql1 = $"select * from stat_pu3000 where Flag={1} and CreatTime>='{dt.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt1 = mysql.ExecuteQuery(sql1);

            string sql = $"select * from stat_chanliang where DeviceId={DeviceID.油漆线} and CreatTime>='{dt.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt2 = mysql.ExecuteQuery(sql);

            PU3000VM_Month pU3000 = new PU3000VM_Month();
            if (dt1 != null && dt1.Rows.Count > 0 && dt2 != null && dt2.Rows.Count > 0)
            {
                float Youqiactrueliy = 0;
                float Guhuajiactrueliy = 0;
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    Youqiactrueliy += Convert.ToSingle(dt1.Rows[i]["Youqiactrueliy"]);
                    Guhuajiactrueliy += Convert.ToSingle(dt1.Rows[i]["Guhuajiactrueliy"]);
                   // pU3000.YouqiConsume.Add(Convert.ToSingle(dt1.Rows[i]["Youqiactrueliy"]) / Convert.ToSingle(dt2.Rows[i]["ChanLiang"]));
                    pU3000.YouqiConsume.Add((Convert.ToSingle(dt1.Rows[i]["Youqiactrueliy"]) + Convert.ToSingle(dt1.Rows[i]["Guhuajiactrueliy"])) / ((Convert.ToInt32(dt2.Rows[i]["ChanLiang"]) == 0 ? 1 : Convert.ToInt32(dt2.Rows[i]["ChanLiang"]))));
                    //pU3000.GuhuaConsume.Add(Convert.ToSingle(dt1.Rows[i]["Guhuajiactrueliy"]));
                }
                pU3000.TotalYouqiConsume = Youqiactrueliy/1000.0f;
                pU3000.TotalGuhuaConsume = Guhuajiactrueliy / 1000.0f;;
                return MessageModel.CreateSuccessResult(pU3000);
            }
            return new MessageModel("未查询到数据");
        }



        /// <summary>
        /// 获取当月油漆单耗使用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel MonthYouQiUsed()
        {
            MysqlHelper mysql = new MysqlHelper();
            DateTime dt = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + "1" + " 00:00:00");
            string sql1 = $"select * from stat_pu3000 where Flag={1} and CreatTime>='{dt.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt1 = mysql.ExecuteQuery(sql1);
            string sql = $"select * from stat_chanliang where DeviceId={DeviceID.油漆线} and CreatTime>='{dt.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt2 = mysql.ExecuteQuery(sql);

            List<float> data = new List<float>();
            if (dt1 != null && dt1.Rows.Count > 0 && dt2!=null && dt2.Rows.Count>0)
            {
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    data.Add((Convert.ToSingle(dt1.Rows[i]["Youqiactrueliy"])+ Convert.ToSingle(dt1.Rows[i]["Guhuajiactrueliy"]))/ (Convert.ToInt32(dt2.Rows[i]["ChanLiang"])==0?1: Convert.ToInt32(dt2.Rows[i]["ChanLiang"])));
                }
                return MessageModel.CreateSuccessResult(data);
            }
            return new MessageModel("未查询到数据");
        }


        /// <summary>
        /// 获取24小时配比 趋势图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel GetPeibiChart()
        {

            float lowPeibi = 0;
            float upPeibi = 0;
            MysqlHelper mysql = new MysqlHelper();
            DateTime time1 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            DateTime time2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            // 
            string sql1 = $"select * from stat_pu3000 where Flag={4} and CreatTime>='{time1.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{time2.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt1 = mysql.ExecuteQuery(sql1);
            // 自动
            //string sql2 = $"select * from stat_pu3000 where Flag={3} and CreatTime>='{time1.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{time2.ToString("yyyy-MM-dd HH:mm:ss")}'";
            //DataTable dt2 = mysql.ExecuteQuery(sql2);

            List<PU3000PeiBiChart> pU3000 = new List<PU3000PeiBiChart>();


            var res = NetFactory.redisPool.ReadKey("MTCD:PU3000Config");
            if (res.IsSuccess)
            {
                JObject obj = JObject.Parse(res.Content);
                lowPeibi = Convert.ToSingle(obj["LowPeibi"]);
                upPeibi = Convert.ToSingle(obj["UpPeibi"]);
            }


            if (dt1 != null && dt1.Rows.Count > 0)
            {

                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    pU3000.Add(new PU3000PeiBiChart
                    {
                        Time = Convert.ToDateTime(dt1.Rows[i]["CreatTime"]).ToString("HH:mm:ss"),
                        Peibi_Hand = Convert.ToSingle(dt1.Rows[i]["Peibi"].ToString()),
                        UpPeibi=upPeibi,
                        LowPeibi=lowPeibi
                    });
                }



                return MessageModel.CreateSuccessResult(pU3000);
            }

            return new MessageModel("未查询到数据");
        }


        /// <summary>
        /// 动态获取设备 数据  因为设备字段不统一
        /// </summary>
        /// <param name="deviceid"></param>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<OtherPageModel<PU3000TableData>> GetPU3000TableData(int type, int page = 1, int size = 20, string startTime = "2021-11-12 15:00:00", string endTime = "2021-11-12 17:50:00")
        {
            OtherPageModel<PU3000TableData> pageModel = new OtherPageModel<PU3000TableData>();
            PU3000TableData dynamicTable = new PU3000TableData();
            dynamicTable.tableColumns = new List<TableColumns>();
            dynamicTable.tableData = new List<TableData1>();
            MysqlHelper mysql = new MysqlHelper();
            int dataCount = 0;
            DataTable dt = null;
            if (type == 1) //每日产量
            {
               dt = mysql.ExecuteQueryPage("stat_chanliang", $"DeviceId={1008} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dynamicTable.tableColumns.Add(new TableColumns{ label = "设备", prop = "Value1" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "产量值", prop = "Value2" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "时间", prop = "Value3" });
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        TableData1 data = new TableData1();
                        data.Value1 = "PU3000";
                        data.Value2 = dt.Rows[i]["ChanLiang"].ToString();
                        data.Value3 = dt.Rows[i]["CreatTime"].ToString();
                        dynamicTable.tableData.Add(data);
                    }
                    pageModel.data = dynamicTable;
                }
            }
            else if (type == 2) //实时配比 
            {
                dt = mysql.ExecuteQueryPage("stat_pu3000", $"Flag={0} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dynamicTable.tableColumns.Add(new TableColumns { label = "设备", prop = "Value1" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "油漆消耗", prop = "Value2" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "固化剂消耗", prop = "Value3" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "配比", prop = "Value4" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "时间", prop = "Value5" });
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        TableData1 data = new TableData1();
                        data.Value1 = "PU3000";
                        data.Value2 = dt.Rows[i]["Youqiactrueliy"].ToString();
                        data.Value3 = dt.Rows[i]["Guhuajiactrueliy"].ToString();
                        data.Value4 = dt.Rows[i]["Peibi"].ToString();
                        data.Value5 = dt.Rows[i]["CreatTime"].ToString();
                        dynamicTable.tableData.Add(data);
                    }
                    pageModel.data = dynamicTable;
                }
            }
            else if (type == 3) //每日 油漆固化剂 
            {
                dt = mysql.ExecuteQueryPage("stat_pu3000", $"Flag={1} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dynamicTable.tableColumns.Add(new TableColumns { label = "设备", prop = "Value1" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "油漆消耗", prop = "Value2" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "固化剂消耗", prop = "Value3" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "时间", prop = "Value4" });
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        TableData1 data = new TableData1();
                        data.Value1 = "PU3000";
                        data.Value2 = dt.Rows[i]["Youqiactrueliy"].ToString();
                        data.Value3 = dt.Rows[i]["Guhuajiactrueliy"].ToString();
                        data.Value4 = dt.Rows[i]["CreatTime"].ToString();
                        dynamicTable.tableData.Add(data);
                    }
                    pageModel.data = dynamicTable;
                }
            }
            else if (type == 4) //pu3000 压力实时数据
            {
                dt = mysql.ExecuteQueryPage("data_pu3000_all", $"CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dynamicTable.tableColumns.Add(new TableColumns { label = "设备", prop = "Value1" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "A泵压力", prop = "Value2" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "B泵压力", prop = "Value3" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "油漆原料", prop = "Value4" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "油漆搅拌", prop = "Value5" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "固化剂原料", prop = "Value6" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "固化剂搅拌", prop = "Value7" });
                    dynamicTable.tableColumns.Add(new TableColumns { label = "时间", prop = "Value8" });
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        TableData1 data = new TableData1();
                        data.Value1 = "PU3000";
                        data.Value2 = dt.Rows[i]["Youqi_press"].ToString();
                        data.Value3 = dt.Rows[i]["Guhua_press"].ToString();
                        data.Value4 = dt.Rows[i]["Youqi_yuanliao"].ToString();
                        data.Value5 = dt.Rows[i]["Youqi_jiaoban"].ToString();
                        data.Value6 = dt.Rows[i]["Guhua_yuanliao"].ToString();
                        data.Value7 = dt.Rows[i]["Guhua_jiaoban"].ToString();
                        data.Value8 = dt.Rows[i]["CreatTime"].ToString();
                        dynamicTable.tableData.Add(data);
                    }
                    pageModel.data = dynamicTable;
                }
            }

            pageModel.dataCount = dataCount;
            pageModel.page = page;
            pageModel.PageSize = size;
            pageModel.pageCount = dataCount % pageModel.PageSize == 0 ? dataCount / pageModel.PageSize : dataCount / pageModel.PageSize + 1;

            if (dt == null || dt.Rows.Count ==0)
                return MessageModel.CreateFailedResult<OtherPageModel<PU3000TableData>>("");
            return MessageModel.CreateSuccessResult(pageModel);

        }





    }
}
